import store from "@/store";
import { authLogin } from "@/api/user";
import { getUserPhoneNumber } from "@/api/public";
import util from "@/utils/util";
import umaTrack from "@/utils/umaTrack.js";
import { saveLoginEndTime } from "./auth.js";
import cache from "@/utils/cache";

// 环境配置



function getWxUrlCode() {
  var url = location.search; //根据自己的配置调整
  var wxCode = new Object();
  if (url.indexOf("?") != -1) {
    var str = url.substr(1);
    var strs = str.split("&");
    for (var i = 0; i < strs.length; i++) {
      wxCode[strs[i].split("=")[0]] = strs[i].split("=")[1];
    }
  }
  return wxCode;
}

export async function wxAuthorize(num) {
  let appid = "wx3843eed9287d8daa"; //自己的微信APPid  可以通过接口让后端给，也可以前端写死
  let code = getWxUrlCode().code; //是否存在code
  let local = window.location.href; //根据自己的配置调整
  if (code == null || code === "") {
    //不存在就打开上面的地址进行授权
    window.location.href =
      "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
      appid +
      "&redirect_uri=" +
      encodeURIComponent(local) +
      "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
    //snsapi_base （不弹出授权页面，直接跳转，只能获取用户openid），
    //snsapi_userinfo （弹出授权页面，可通过openid拿到昵称、性别、所在地。
    //并且， 即使在未关注的情况下，只要用户授权，也能获取其信息 ）
  } else {
    handleLogin(code);
  }
}

async function handleLogin(code) {
  const params = {
    code,
    ...(cache.get("params") && JSON.parse(cache.get("params"))),
  };

  const res = await authLogin(params);

  if (res.code !== 200) {
    throw new Error(res.message || "登录失败");
  }

  if (res.data.type === "login") {
    await handleLoginSuccess(res.data);
  } else if (res.data.type === "register") {
    handleRegister(res.data.key);
  }
}

async function handleLoginSuccess(data) {
  console.log('login success');
  
  await saveLoginEndTime(data.expiresIn);
  await store.commit("LOGIN", {
    token: data.tokenHead + data.token,
  });
  await store.commit("SETUID", data.memberId);
  await umaTrack.loginTrack("微信公众号");
  await store.dispatch("USERINFO");
  await util.Tips("登录成功");
  uni.$emit('loginSuccess')
}

function handleRegister(key) {
  uni.redirectTo({
    url: `/pagesWater/users/login?&type=bind&flagType=0&key=${key}`,
  });
}
